package com.zzzyh.forumsystemclient.exception;

import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的 AppException 异常
     */
    @ResponseBody
    @ExceptionHandler(AppException.class)
    public AppResult handleAppException(AppException e) {
        e.printStackTrace();
        log.error("AppException:{}", e.getMessage());
        if(e.getErrorResult() != null)
            return e.getErrorResult();
        if (e.getMessage() == null ||  e.getMessage().equals(""))
            return AppResult.failed(ResultCode.FAILED);
        return e.getErrorResult();
    }

    /**
     * 统一处理其他异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleException(Exception e) {
        e.printStackTrace();
        log.error("Exception:{}", e.getMessage());
        if (e.getMessage() == null ||  e.getMessage().equals(""))
            return AppResult.failed(ResultCode.FAILED);
        return AppResult.failed(e.getMessage());
    }
}
